package com.groovy.domain

import groovy.xml.MarkupBuilder
import groovy.xml.XmlParser
import groovy.xml.XmlSlurper
import org.junit.Test

//Books对象
class Books {
    int count = 5
    def books = [
            new Book(id: System.currentTimeMillis(),title: "Kotlin入门到实战", author: "周伯通"),
            new Book(id: System.currentTimeMillis(),title: "Swift入门到实战", author: "杨过"),
            new Book(id: System.currentTimeMillis(),title: "Groovy入门到实战", author: "小龙女"),
            new Book(id: System.currentTimeMillis(),title: "Scala入门到实战", author: "郭靖"),
            new Book(id: System.currentTimeMillis(),title: "Java入门到实战", author: "瑛姑")
    ]
}

//Book对象
class Book {
    Long id
    String title
    String author
}

class XmlTest {

    @Test
    void createXmlObject() {

        def sw = new StringWriter()
        def markupBuilder = new MarkupBuilder(sw)
        def books = new Books()

        //创建一个Books节点
        markupBuilder.Books(count: books.count) {
            //获取books数据进行遍历
            books.books.forEach { book ->
                //获取book数据，创建一个Book节点
                Book(id:book.id,title: book.title, author: book.author)
            }
        }
        println(sw)
    }

    @Test
    void createXml() {

        def sw = new StringWriter()
        def markupBuilder = new MarkupBuilder(sw)
        //对Books节点添加一个count属性值为5
        markupBuilder.Books(count: 5) {
            //在Books创建Book节点,并且给一个id为1的值
            //在book节点下创建title与author节点
            Book(id: 1) {
                title("Kotlin入门到实战")
                author("周伯通")
            }
            Book(id: 2) {
                title("Java入门到实战")
                author("杨过")
            }
            Book(id: 3) {
                title("Groovy入门到实战")
                author("小龙女")
            }
            Book(id: 4) {
                title("Scala入门到实战")
                author("瑛姑")
            }
            Book(id: 5) {
                title("Swift入门到实战")
                author("郭靖")
            }
        }
        println(sw)
    }

    @Test
    void testCreateXml() {
        def targetFile = new File("src/main/resources/books.xml")
        if (targetFile != null && !targetFile.exists()) {
            targetFile.createNewFile()
        }

        def sw = new StringWriter()
        def markupBuilder = new MarkupBuilder(sw)

        //没有内容
        if (targetFile.text != null && targetFile.text.size() <= 0) {
            // markupBuilder.'?xml'(version:"1.0", encoding:"UTF-8")
            markupBuilder.Books {
                Book(id: System.currentTimeMillis()) {
                    title("入门到精通Hbase")
                    author("欧阳锋")
                }
            }

            targetFile.withWriter { writer ->
                writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>").append("\r\n")
                writer.append(sw.toString())
            }
        } else {
            markupBuilder.Book(id: System.currentTimeMillis()) {
                title("入门到精通Hbase")
                author("欧阳锋")
            }

            //处理已经存在的数据.
            def lines = targetFile.readLines()
            def lengths = lines.size() - 1

            targetFile.withWriter { writer ->
                lines.eachWithIndex { String str, int index ->
                    if (index != lengths) {
                        writer.append(str + "\r\n")
                    } else {
                        //追加存在的内容
                        writer.append(sw.toString() + "\r\n")
                        writer.append(lines.get(lengths))
                    }
                }
            }
        }
    }

    /**
     * 使用XmlParser进行解析
     */
    @Test
    void testParseXml1() {

        def srcFile = new File("src/main/resources/books.xml")
        def targetDir = new File("src/main/resources/", "xml/")
        //创建目录
        targetDir.mkdirs()

        def booksNode = new XmlParser().parse(srcFile)
        //遍历所有Book节点
        booksNode.Book.each { book ->

            //获取id、title、author的内容信息
            def id = book.@id
            def title = book.title.text()
            def author = book.author.text()
            //写入指定文件
            def targetFile = new File(targetDir, "book-${author}-${id}.txt")
            targetFile.withWriter {
                it.append("${id}->${author}->${title}")
            }
        }
    }

    /**
     * 使用XmlSlurper进行解析
     */
    @Test
    void testParseXml2() {

        //获取xml文件路径
        def path = XmlTest.class.getClassLoader().getResource("book.xml").path

        //指定文件路径，指定解析编码进行获内容信息
        def content = new File(path).getText("utf-8")

        //创建XmlSlurper对象
        def xmlSlurper = new XmlSlurper()
        //解析内容信息，获取book节点
        def books = xmlSlurper.parseText(content)
        // println(books.Book[0].@id)
        //获取多个Book节点
        books.Book.forEach { book ->
            //使用GPathResult节点路径去获取id值
            println("Id=${book.@id},书名称=${book.title},书作者=${book.author}")
        }
    }

}
